package leetcode.mapCode.week1.leetcode_200;

import java.util.Arrays;

class Solution {
    private boolean[][] visited;
    private int[][] DIR = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public int numIslands(char[][] grid) {

        int n = grid.length;
        int m = grid[0].length;
        visited = new boolean[n][m];
        for (boolean[] row : visited) {
            Arrays.fill(row, false);
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == '1' && visited[i][j] == false) {
                    ans++;
                    visited[i][j] = true;
                    dfs(grid,i,j);
                }
            }
        }
        return ans ;

    }

    private void dfs(char[][] grid, int x, int y) {
        for (int i = 0; i < 4; i++) {
            int newX = x + DIR[i][0];
            int newY = y + DIR[i][1];
            if (newX >= grid.length || newX < 0) {
                continue;
            }
            if (newY >= grid[0].length || newY < 0) {
                continue;
            }
            if (grid[newX][newY] == '1' && visited[newX][newY] == false) {
                visited[newX][newY] = true;
                dfs(grid, newX, newY);
            }
        }
    }
}